<?php
/**
 * Common methods for database drivers
 *
 * @package Rapide_Database
 * @since 0.4dev rev 83
 */
abstract class Rapide_Database implements Rapide_Database_Interface
{
	protected
		$_aQueryStack = array(),
		$_aParameters = array();

	/**
	 * Creates database object
	 *
	 * @param array $aParameters connection parameters
	 * @param bool $bConnect persistent connection
	 */
	public function __construct(array $aParameters, $bConnect = true)
	{
		$this->_aParameters = $aParameters;
		if($bConnect)
			$this->connect();
	}

	/**
	 * Connect database
	 *
	 */
	public abstract function connect();

	/**
	 * Disconnect database
	 *
	 */
	public abstract function disconnect();

	/**
	 * Exec query
	 *
	 * @param string $sQuery query
	 */
	public function exec($sQuery)
	{
		array_push($this->_aQueryStack, $sQuery);
	}

	/**
	 * Exec query
	 *
	 * @param string $sQuery query
	 */
	public function query($sQuery)
	{
		array_push($this->_aQueryStack, $sQuery);
	}

	protected function _checkParameters($aParameters)
	{
		if(empty($aParameters['driver']))
			$aParameters['driver'] = 'mysql';

		if(empty($aParameters['host']))
			$aParameters['host'] = 'localhost';

		if(empty($aParameters['user']))
		{
			$sError = 'Parameter user has not been set';
			throw new Rapide_Database_Exception($sError);
		}

		if(empty($aParameters['password']))
		{
			$sError = 'Parameter password has not been set';
			throw new Rapide_Database_Exception($sError);
		}

		if(empty($aParameters['database']))
		{
			$sError = 'Parameter database has not been set';
			throw new Rapide_Database_Exception($sError);
		}

		if(!isset($aParameters['persistent']) || !is_bool($aParameters['persistent']))
		{
			$aParameters['persistent'] = false;
		}

		return $aParameters;
	}

	/**
	 * Start transaction
	 *
	 */
	public function begin()
	{
		$this->exec('SET AUTOCOMMIT = 0');
	}

	/**
	 * Commit transaction
	 *
	 */
	public function commit()
	{
		$this->exec('COMMIT');
		$this->exec('SET AUTOCOMMIT = 1');
	}

	/**
	 * Abort transaction
	 *
	 */
	public function abort()
	{
		$this->exec('ROLLBACK');
		$this->exec('SET AUTOCOMMIT = 1');
	}

	/**
	 * Get array of executed queries
	 *
	 * @return array queries
	 */
	public function getQueryStack()
	{
		return $this->_aQueryStack;
	}
}
?>